const express = require('express');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// Serve static files
app.use(express.static('public'));
app.use('/images', express.static('images'));

// Supported image extensions
const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'];

// Function to scan directory for images
function scanImagesInDirectory(dirPath) {
    const images = [];
    
    try {
        if (!fs.existsSync(dirPath)) {
            console.log(`Directory ${dirPath} does not exist. Creating it...`);
            fs.mkdirSync(dirPath, { recursive: true });
            return images;
        }

        const files = fs.readdirSync(dirPath);
        
        files.forEach(file => {
            const filePath = path.join(dirPath, file);
            const stat = fs.statSync(filePath);
            
            if (stat.isFile()) {
                const ext = path.extname(file).toLowerCase();
                if (imageExtensions.includes(ext)) {
                    images.push({
                        name: file,
                        path: `/images/${file}`,
                        size: stat.size,
                        modified: stat.mtime
                    });
                }
            }
        });
    } catch (error) {
        console.error('Error scanning directory:', error);
    }
    
    return images;
}

// API endpoint to get images
app.get('/api/images', (req, res) => {
    const imagesDir = path.join(__dirname, 'images');
    const images = scanImagesInDirectory(imagesDir);
    res.json(images);
});

// API endpoint to get images from custom directory
app.get('/api/images/:directory(*)', (req, res) => {
    const customDir = req.params.directory;
    const images = scanImagesInDirectory(customDir);
    
    // Update image paths to use the custom serve route
    const updatedImages = images.map(image => ({
        ...image,
        path: `/serve-image/${encodeURIComponent(customDir)}/${encodeURIComponent(image.name)}`
    }));
    
    res.json(updatedImages);
});

// Route to serve images from custom directories
app.get('/serve-image/:directory(*)/:filename', (req, res) => {
    const directory = decodeURIComponent(req.params.directory);
    const filename = decodeURIComponent(req.params.filename);
    const imagePath = path.join(directory, filename);
    
    // Check if file exists and is an image
    if (fs.existsSync(imagePath)) {
        const ext = path.extname(filename).toLowerCase();
        if (imageExtensions.includes(ext)) {
            res.sendFile(path.resolve(imagePath));
        } else {
            res.status(404).send('File not found');
        }
    } else {
        res.status(404).send('File not found');
    }
});

// Serve main page
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Start server
app.listen(PORT, () => {
    console.log(`Image Wall server running at http://localhost:${PORT}`);
    console.log(`Place your images in the 'images' directory`);
});
